import React, { createContext, useContext, useState, useEffect } from "react";

interface User {
  id: string;
  name: string;
  role: "admin" | "teacher" | "student";
  email: string;
  phone?: string;
  avatar?: string;
  permissions: string[];
  department?: string;
  title?: string;
  class?: string;
  major?: string;
}

interface UserContextType {
  user: User | null;
  loading: boolean;
  setUser: (user: User | null) => void;
  login: (username: string, password: string, role: string) => Promise<void>;
  logout: () => void;
  hasPermission: (permission: string) => boolean;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

const mockUsers: Record<string, User> = {
  admin: {
    id: "admin1",
    name: "管理员",
    role: "admin",
    email: "admin@example.com",
    permissions: [
      "teacher.manage",
      "student.manage",
      "course.manage",
      "discussion.manage",
      "system.manage",
    ],
  },
  teacher: {
    id: "teacher1",
    name: "教师",
    role: "teacher",
    email: "teacher@example.com",
    permissions: [
      "course.view",
      "course.edit",
      "student.view",
      "discussion.view",
      "discussion.create",
      "discussion.reply",
      "discussion.like",
    ],
  },
  student: {
    id: "student1",
    name: "学生",
    role: "student",
    email: "student@example.com",
    permissions: [
      "course.view",
      "discussion.view",
      "discussion.create",
      "discussion.reply",
      "discussion.like",
    ],
  },
  // 添加更多用户模拟数据
  admin2: {
    id: "4",
    name: "副管理员",
    role: "admin",
    email: "admin2@example.com",
    permissions: [
      "teacher.manage",
      "student.manage",
      "course.manage",
      "discussion.manage",
    ],
  },
  teacher2: {
    id: "5",
    name: "王老师",
    role: "teacher",
    email: "teacher2@example.com",
    permissions: [
      "course.view",
      "course.edit",
      "homework.manage",
      "exam.manage",
      "discussion.manage",
      "grade.manage",
    ],
  },
  student2: {
    id: "6",
    name: "张同学",
    role: "student",
    email: "student2@example.com",
    permissions: [
      "course.view",
      "homework.submit",
      "exam.take",
      "discussion.create",
      "discussion.reply",
    ],
  },
};

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 检查本地存储中是否有用户信息
    const storedUser = localStorage.getItem("user");
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
    setLoading(false);
  }, []);

  const login = async (username: string, password: string, role: string) => {
    try {
      // TODO: 实际的登录 API 调用
      // 模拟登录成功
      const mockUser = mockUsers[role as keyof typeof mockUsers];
      if (!mockUser) {
        throw new Error("无效的用户角色");
      }

      // 使用输入的用户名覆盖模拟数据中的名字
      const userWithCustomName = {
        ...mockUser,
        name: username,
      };

      setUser(userWithCustomName);
      localStorage.setItem("user", JSON.stringify(userWithCustomName));
    } catch (error) {
      console.error("登录失败:", error);
      throw error;
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem("user");
  };

  const hasPermission = (permission: string): boolean => {
    if (!user) return false;
    return user.permissions.includes(permission);
  };

  return (
    <UserContext.Provider
      value={{
        user,
        loading,
        setUser,
        login,
        logout,
        hasPermission,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
};

export default UserContext;
